package _stack_queue;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.LinkedList;

public class leetcode_239_Java {
    /**
     * https://leetcode.cn/problems/sliding-window-maximum/
     * https://programmercarl.com/0239.%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E6%9C%80%E5%A4%A7%E5%80%BC.html
     * 239. 滑动窗口最大值
     * <p>
     * 输入：nums = [1,3,-1,-3,5,3,6,7], k = 3
     * 输出：[3,3,5,5,6,7]
     * 解释：
     * 滑动窗口的位置                最大值
     * ---------------               -----
     * [1  3  -1] -3  5  3  6  7       3
     * 1 [3  -1  -3] 5  3  6  7       3
     * 1  3 [-1  -3  5] 3  6  7       5
     * 1  3  -1 [-3  5  3] 6  7       5
     * 1  3  -1  -3 [5  3  6] 7       6
     * 1  3  -1  -3  5 [3  6  7]      7
     * 示例 2：
     * <p>
     * 输入：nums = [1], k = 1
     * 输出：[1]
     */
    @Test
    public void test_1() {
        int[] actual = maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 3);
        int[] expect = new int[]{3, 3, 5, 5, 6, 7};
        Assert.assertEquals(Arrays.toString(expect), Arrays.toString(actual));
    }

    @Test
    public void test_2() {
        int[] actual = maxSlidingWindow(new int[]{1}, 1);
        int[] expect = new int[]{1};
        Assert.assertEquals(Arrays.toString(expect), Arrays.toString(actual));
    }


    private int[] maxSlidingWindow(int[] nums, int k) {
        int size = nums.length;
        if (size == 1) {
            return nums;
        }
        // 8, k =  3, r = 6
        int[] result = new int[size - k + 1];  // TODO:最容易出错
        MyQueue myQueue = new MyQueue();
        int index = 0;
        for (int i = 0; i <= k - 1; i++) {
            myQueue.offer(nums[i]);
        }
        result[index++] = myQueue.peek();

        for (int i = k; i <= size - 1; i++) {
            // i = 3, remove i 0
            // i = 4, remove i 1
            myQueue.poll(nums[i - k]);  // TODO:最容易出错
            myQueue.offer(nums[i]);
            result[index++] = myQueue.peek();
        }
        return result;
    }

    static class MyQueue {
        LinkedList<Integer> q = new LinkedList<>();

        int peek() {
            return q.peek();
        }

        void offer(int n) {
            while (!q.isEmpty() && n > q.peekLast()) { // TODO:最容易出错
                q.removeLast();
            }
            q.addLast(n);
        }

        void poll(int n) {
            if (!q.isEmpty() && q.peekFirst() == n) {
                q.removeFirst();
            }
        }
    }
}
